//
//  JournalListController.m
//  DataStatistics
//
//  Created by Kang on 16/4/14.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "JournalListController.h"
#import "JournalViewModel.h"              //日志列表模型
#import "EquipmenDetailsViewModel.h"    
#import "JournalListCell.h"
//#import "EquipmenDetailsVC.h"            // 详情
//#import "DTKDropdownMenuView.h"  //下拉框工具
#import "UIimageView+WebCache.h"
#import "SystemInfoController.h" //
#define  reuseIdentifier  @"journalList"
#import "FootView.h"
#import "GUAAlertView.h"


@interface JournalListController ()<UITableViewDataSource,UITableViewDelegate>
{
    //CoverView *cover;
    NSString *key;
    UIView *WarningView;
    FootView  *Fview;
}

/**
 *   判断刷新 ，true -刷新  float -加载
 */
@property (assign, nonatomic) BOOL isToUpdate;
/**
 *  数据页数
 */
@property (assign, nonatomic)  int page;
/**
 *  日志列表存放数据
 */
@property (strong, nonatomic) NSMutableArray *publicmodelAry;
/**
 *  获取点击的日志id
 */
@property (assign, nonatomic) int JLC_log_id;
@property (strong, nonatomic)UIButton *notDataBtn;

@end

@implementation JournalListController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self updateUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.title = [NSUD objectForKey:@"device_name"];
//    self.title =NSLocalizedString(@"SysLead_title", @"报警日志");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - TableView Data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.publicmodelAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cellHeight = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return CGRectGetHeight(cellHeight.frame);
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JournalListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"journalList"];
    JouList * lis = self.publicmodelAry[indexPath.row];
    
    NSString *urlStr = [GET_HEND_IMAGE_IP stringByAppendingString:lis.employee_img];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    cell.dayimage.layer.cornerRadius=cell.dayimage.frame.size.width/6;// 将图层的边框设置为圆角
    cell.dayimage.layer.masksToBounds=YES;//隐藏边框
    [cell.dayimage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon-morentouxiang.png"] completed:nil];
    
    [cell vlueWithList:self.publicmodelAry[indexPath.row]];
    
    cell.backgroundColor = RGB(33, 38, 44, 1);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//取消点击效果

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}



//设置段头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        return 60;

    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"667.0")){
        return 65;

    }else {
        return 70;
    }

}


//添加段头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    Fview = [[NSBundle mainBundle]loadNibNamed:@"FootView" owner:self options:nil][0];
    Fview.backgroundColor =  RGB(33, 38, 44, 1);
    [Fview.WarningButton setTintColor:[UIColor whiteColor]];
    [Fview.WarningButton setUserInteractionEnabled:NO];
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    
    NSString *name = [defaults objectForKey:@"name"];//根据键值取出name
    
   long hour = [name integerValue]/3600;
   long minute = ([name integerValue]%3600)/60;
    
    
    if (hour >=1&& minute>0) {
        NSString *str1 = [NSString stringWithFormat:@"停机 %ld小时%ld分钟 后报警",(long)hour ,(long)minute];
 
        NSRange range = [str1 rangeOfString:@"后"];
        
                NSString *str = [str1 substringToIndex:range.location];
                NSInteger i = str.length;
        
                NSMutableAttributedString *promptLanguageMut = [[NSMutableAttributedString alloc]initWithString:str1];
                // 设置 上面标题
                [promptLanguageMut addAttribute:NSForegroundColorAttributeName value:RGB(230, 190,60,1) range:NSMakeRange(2, i-2)];
        
                [Fview.WarningButton setAttributedTitle:promptLanguageMut forState:UIControlStateNormal];
        
    }else if (hour>=1){
        
        NSString *str1 =[NSString stringWithFormat:@"停机 %ld小时 后报警",(long)hour];
        
        NSRange range = [str1 rangeOfString:@"后"];
        
        NSString *str = [str1 substringToIndex:range.location];
        NSInteger i = str.length;
        
        NSMutableAttributedString *promptLanguageMut = [[NSMutableAttributedString alloc]initWithString:str1];
        // 设置 上面标题
        [promptLanguageMut addAttribute:NSForegroundColorAttributeName value:RGB(230, 190,60,1) range:NSMakeRange(2, i-2)];
        
        
        [Fview.WarningButton setAttributedTitle:promptLanguageMut forState:UIControlStateNormal];

    
    }else{
        NSString *str1 = [NSString stringWithFormat:@"停机 %ld分钟 后报警",(long)minute];
        
        NSRange range = [str1 rangeOfString:@"后"];
        
        NSString *str = [str1 substringToIndex:range.location];
        NSInteger i = str.length;
        
        NSMutableAttributedString *promptLanguageMut = [[NSMutableAttributedString alloc]initWithString:str1];
        // 设置 上面标题
        [promptLanguageMut addAttribute:NSForegroundColorAttributeName value:RGB(230, 190,60,1) range:NSMakeRange(2, i-2)];
        
        
        [Fview.WarningButton setAttributedTitle:promptLanguageMut forState:UIControlStateNormal];
        
        
    }

    return Fview;
}


#pragma mark - Other
// 更新数据，布局UI
- (void)updateUI {
    
    self.isToUpdate = YES;
    self.page = 1;
    self.journalTableView.tableFooterView=[[UIView alloc]init];//隐藏多余的分割线

    self.journalTableView.backgroundColor = RGB(33, 38, 44, 1);
    
    if (self.journalDeviceCode == nil) {
        self.journalDeviceCode = [[NSUserDefaults standardUserDefaults] objectForKey:@"journalDevice"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"journalDevice"];
    }
    if (self.journalUnread > 0) {
        NSDictionary *dic =@{@"deviceCode":self.journalDeviceCode};
        [JournalViewModel requestWithUrlForRemoveUnreadNum:self andParam:dic failure:^(NSString *mag) {
            NSLog(@"清除未读结果代码:----->%@",mag);
        }];
    }
    [self refreshTableView];
}



- (void)refreshTableView {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isToUpdate = YES;
        self.page = 1;
        [self requestUrlViewWithPage:self.page];
    }];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    [header beginRefreshing];
    self.journalTableView.header = header;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.isToUpdate = NO;
        self.page++;
        
        
        [self requestUrlViewWithPage:self.page];
    }];
    self.journalTableView.footer = footer;
    
}


- (void)requestUrlViewWithPage:(int)page {
    
    [JournalViewModel requestWithUrlForJournal:self andParam:@{@"deviceCode":self.journalDeviceCode,@"current_page":@(page)} success:^(JournalModel *model) {
       
        [self.journalTableView.footer endRefreshing];
        [self.journalTableView.header endRefreshing];

        
            if (_isToUpdate) {
                if ([model.JouList count] <= 0) {
                    self.publicmodelAry = nil;
                    [self.notDataBtn removeFromSuperview];
                    [self.journalTableView addSubview:[self notDataBtn]];
                    [self.journalTableView reloadData];
                }else {
                    self.publicmodelAry = nil;
                    self.publicmodelAry = model.JouList;
                    [self.notDataBtn removeFromSuperview];
                    [self.journalTableView reloadData];
                }
        }else {
            if ([model.JouList count] <= 0) {
                [self.journalTableView.footer endRefreshingWithNoMoreData];

            }else {
                NSMutableArray *mutaAry = [[NSMutableArray alloc] init];
                [mutaAry addObjectsFromArray:self.publicmodelAry];
                [mutaAry addObjectsFromArray:model.JouList];
                self.publicmodelAry = mutaAry;
                [self.journalTableView reloadData];
            }
        }
        
    } failure:^(NSString *error) {
        
        [self.notDataBtn removeFromSuperview];
        
        if (self.publicmodelAry.count <=0) {
            [self.journalTableView addSubview:[self notDataBtn]];
        }
        
        [self.journalTableView.footer endRefreshing];
        [self.journalTableView.header endRefreshing];
        //新加
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
    }];
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _publicmodelAry = [[NSMutableArray alloc]init];
    }
    return self;
    
}


#pragma  mark - get / set
- (UIButton *)notDataBtn {
    if (!_notDataBtn) {
        _notDataBtn = [UtilToolsClss noDataBtn:NSLocalizedString(@"No Journal", @"没有日志")];
    }
    return _notDataBtn;
}


#pragma mark -Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier compare:@"gotoLogInfoC"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:self.journalDeviceCode forKey:@"logInfoDeviceCode"];
        [vc setValue:[NSNumber numberWithInt:self.JLC_log_id] forKey:@"logInfoID"];
    }else if ([segue.identifier compare:@"gotoCoustomerDetails"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:self.journalDeviceCode forKey:@"coustomerDeviceCode"];
    }else if ([segue.identifier compare:@"gotoModifySystemInfo"] == NO) {
        id vc = segue.destinationViewController;
         [vc setValue:self.journalDeviceCode forKey:@"sys_deviceCode"];
         [vc setValue:@"修改昵称" forKey:@"marked"];
    }
}
    

- (IBAction)delete:(id)sender {
    
    
    if (self.publicmodelAry.count <=0) {
        [MBProgressHUD yty_showErrorWithTitle:@"当前设备没有报警日志" detailsText:nil toView:nil];
    }else{


    GUAAlertView *v = [GUAAlertView alertViewWithTitle:@"提示"
                                               message:@" 确定清空当前设备报警日志？"
                                           buttonTitle:@"确定"
                                   buttonTouchedAction:^{
                                       NSLog(@"button touched");
                                       
                                       
                                       
                                       NSDictionary* dic = @{@"deviceNo":  [NSUD objectForKey:@"device_name"],@"deleteAlarms":@"all",};
                                       
                                       [JournalViewModel requestWithUrlForChangePassword:self andParam:dic success:^(JournalModel *model) {
                                           
                                           if ([model isEqual:@(1)]) {
                                               
                                               [self updateUI];
                                               
                                           }
                                           
                                           
                                       } failure:^(NSString *error) {
                                           
                                           [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
                                           
                                       }];
                                       

                                       
                                   } dismissAction:^{
                                       NSLog(@"dismiss");
                                       
                                   }];
    [v show];
    

    }
}

//}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/




@end
